//
//  HMComposeTextView.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/10/4.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
//实时看到效果
@IBDesignable
class HMComposeTextView: UITextView {

    //占位label
    private lazy var placeHolderLabel:UILabel = {
       let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = "好好学习天天向上"
        label.textColor = UIColor.lightGray
        label.numberOfLines = 0
        return label
    }()

    //提供占位属性
    @IBInspectable var placeHolder:String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    //重写font属性
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    //重写text属性
    override var text:String? {
        didSet {
            placeHolderLabel.isHidden = hasText
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setUpUI()
    }
    
    private func setUpUI() {
        //监听文字改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        //backgroundColor = RandomColor()
        addSubview(placeHolderLabel)
        //控件布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    }
    
    @objc private func textChange() {
        placeHolderLabel.isHidden = hasText
    }
    
    required init?(coder aDecoder: NSCoder) {
        //xib写法
        super.init(coder: aDecoder)
        setUpUI()
    }
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
